﻿///
///sku模块处理
///
(function ($) {
    $.fn.skuHandler = function (options) {
        var $this = this;

        if ($this.data('skuHandler')) {
            return $this.data('skuHandler');
        }

        $this.data('skuHandler', $this);


        $this.setting = $.extend({},
        //默认配置
        {
        //产品列表
        plist: [],
        //分组列表
        glist: [],
        //分组模板
        groupTemplate: '<tr group={id}><td>{name}</td><td><ul>{itemlist}</ul></td></tr>',
        //项模板
        itemTemplate: '<li><a item={id} href="javascript:void(0);">{name}</a></li>',
        //项激活class
        activeClass: 'active',
        //项不可用class
        unvalidClass: 'unvalid',
        //取消选中
        unselectProduct: function () {
        },
        //选中商品
        selectProduct: function (product) {
        }
    },
        options);

    //sku产品列表
    $this.plist = options.plist;
    //sku分组/子项数据
    $this.glist = options.glist;

    if ($this.plist.length == 0) {
        alert('数据异常');
        return;
    }
    //sku只有一项时，不做后续处理
    if ($this.plist.length == 1) {
        $this.setting.selectProduct($this.plist[0]);
        return;
    }

    $($this.plist).each(function () {
        this.skuItems = $.parseJSON(this.ParamCode);
    });

    //所有有效的sku项(不重复)
    $this.itemlist = [];
    $($this.plist).each(function () {
        $(this.skuItems).each(function () {
            var item = this;
            var existed = false;
            //判断项是否存在，插入不存在的项
            $($this.itemlist).each(function () {
                if (this.ItemId == item.ItemId) {
                    existed = true;
                    return false;
                }
            });
            if (!existed) {
                $this.itemlist.push(this);
            }
        });
    });


    $($this.glist).each(function () {
        var group = this;

        //过滤无效的sku项
        var unvaliditemlist = [];

        $(group.Items).each(function () {

            //检查item是否存在于validskulist中，不存在则无效
            var item = this;
            var existed = false;
            $($this.itemlist).each(function () {
                if (item.Id == this.ItemId) {
                    existed = true;
                    return false;
                }
            });
            if (!existed) {
                unvaliditemlist.push(item);
            }
        });

        //从items中删除无效的项
        $(unvaliditemlist).each(function () {
            var item = this;
            group.Items = $.grep(group.Items, function (cur, i) {
                return cur.Id != item.Id;
            });
        });
    });

    //输出html
    $($this.glist).each(function () {
        var group = this;
        var itemhtml = '';
        $(group.Items).each(function () {
            itemhtml += $this.setting.itemTemplate.format({ name: this.ItemName, id: this.Id });
        });
        $this.append($this.setting.groupTemplate.format({ name: group.Group.SkuName, id: group.Group.Id, itemlist: itemhtml }));
    });

    //设置各sku项相关有效的数组
    $('[item]', $this).each(function () {
        var jitem = $(this);
        var validlist = [];

        //遍历plist，找出含有当前项的而且不在同一分组其他sku项
        $($this.plist).each(function () {
            var productSku = this;
            $(productSku.skuItems).each(function () {
                if (this.ItemId == jitem.attr('item')) {
                    validlist.push(productSku);
                    return false;
                }
            });
        });
        jitem.data('validlist', validlist);
    });

    //某项点击
    $('[item]', $this).click(function () {
        if ($(this).hasClass($this.setting.unvalidClass)) {
            return;
        }
        //取消同组的其他项
        var groupid = $(this).parents('[group]').attr('group');
        $('[item!=' + $(this).attr('item') + ']', $('[group=' + groupid + ']', $this)).removeClass($this.setting.activeClass);

        $(this).toggleClass($this.setting.activeClass);

        //重置选项
        resetItems($(this));

        //当选中的项数=分组数，即说明已选中某sku项
        if ($('.' + $this.setting.activeClass + '[item]', $this).length == $this.glist.length) {
            var itemhash = {};
            $('.' + $this.setting.activeClass + '[item]', $this).each(function () {
                itemhash[$(this).attr('item')] = true; ;
            });

            //查找商品
            var selectedProduct = false;
            $($this.plist).each(function () {
                var product = this;
                var match = true;
                $(product.skuItems).each(function () {
                    if (!itemhash[this.ItemId]) {
                        match = false;
                        return false;
                    }
                });
                if (match) {
                    selectedProduct = product;
                    return false;
                }
            });
            if (selectedProduct != false) {
                $this.setting.selectProduct(selectedProduct);
            } else {
                $this.setting.unselectProduct();
            }
        } else {
            $this.setting.unselectProduct();
        }
    });

    //重置各项的可用性
    var resetItems = function () {
        //计算交集，找出可用的sku项
        //var validlist = $this.plist;

        //计算各个分组的可用项
        $($this.glist).each(function () {
            var group = this;

            //获取不在此分组的选中sku产品交集
            var validproductlist = $this.plist;
            $('.' + $this.setting.activeClass + '[item]', $this).each(function () {
                var groupid = $(this).parents('[group]').attr('group');
                if (groupid != group.Group.Id) {
                    validproductlist = crosArray(validproductlist, $(this).data('validlist'));
                }
            });

            //设置各项是否可用
            $(group.Items).each(function () {
                var item = this;
                item.isvalid = false;

                //validproductlist中是否包含当前项，是则可用，否则不可用
                $(validproductlist).each(function () {
                    $(this.skuItems).each(function () {
                        if (item.Id == this.ItemId) {
                            item.isvalid = true;
                            return false;
                        }
                    });
                    if (item.isvalid) {
                        return false;
                    }
                });
                var jitem = $('[item=' + item.Id + ']', $this);
                if (item.isvalid) {
                    jitem.removeClass($this.setting.unvalidClass);
                } else {
                    jitem.addClass($this.setting.unvalidClass);
                    //取消选中
                    jitem.removeClass($this.setting.activeClass);
                }
            });
        });


    }

    //数组交集
    var crosArray = function (arr1, arr2) {
        var hash = {}, result = [];
        for (var i = 0; arr1[i] != null; i++) hash[arr1[i].Id] = true;
        for (var i = 0; arr2[i] != null; i++) {
            if (hash[arr2[i].Id]) {
                result.push(arr2[i]);
            }
        }
        return result;
    }



}
})(jQuery);